import { AbstractControl } from '@angular/forms'

export interface AdFormError {
  handle: (control: AbstractControl) => string | void
}

export class AdFormErrorImpl implements AdFormError {
  handle(control: AbstractControl): string | void {
    const errorMapper = {
      required: '不能为空',
      minlength: '长度过短',
      maxlength: '长度过长',
      pattern: '格式不正确',
      min: '不能小于',
      max: '不能大于',
    }
    const errorsMapperKeys = Object.keys(errorMapper)
    const errorKey = errorsMapperKeys.find((key) => control.hasError(key))
    const errors = control.errors || {}
    const firstError = Object.keys(errors)[0]
    let message = errorMapper[errorKey] || errors[firstError].error?.() || firstError
    if (errorKey === 'min') {
      message += control.errors?.min?.min
    } else if (errorKey === 'max') {
      message += control.errors?.max?.max
    }
    return message
  }
}
